package net.yb.service.impl;

import net.yb.dao.UserDao;
import net.yb.dao.impl.UserDaoImpl;
import net.yb.entity.User;
import net.yb.exception.NameExistsException;
import net.yb.exception.PhoneExistsException;
import net.yb.service.UserService;

import java.util.List;

/**
 * 用户业务层的实现类
 */
public class UserServiceImpl implements UserService {

    // 创建UserDao对象，调用DAO层的方法
    private UserDao userDao = new UserDaoImpl();

    @Override
    public boolean addUser(User user) {
        /**
         * 判断用户名是否已存在
         */
        User u = userDao.selectByName(user.getName());
        if (u != null){
            throw new NameExistsException("用户名已存在！"); // 抛出异常，指定异常消息
        }

        /**
         * 判断找手机号是否已存在
         */
        u = userDao.selectByPhone(user.getPhone());
        if (u != null){
            throw new PhoneExistsException("手机号已存在！");
        }

        /**
         * 保存用户
         */
        boolean flag = userDao.insert(user);

        return flag;
    }

    @Override
    public List<User> findAll() {
        return userDao.selectAll();
    }

    @Override
    public User findById(int id) {
        return userDao.selectById(id);
    }

    @Override
    public void modify(User user) {
        /**
         * 判断用户名是否已存在
         */
        User u = userDao.selectByName(user.getName());
        if (u != null){
            throw new NameExistsException("用户名已存在！"); // 抛出异常，指定异常消息
        }

        /**
         * 判断找手机号是否已存在
         */
        u = userDao.selectByPhone(user.getPhone());
        if (u != null){
            throw new PhoneExistsException("手机号已存在！");
        }

        userDao.updateById(user);
    }

    @Override
    public void removeById(int id) {
        userDao.deleteById(id);
    }

    @Override
    public List<User> findCondition(String name, String address) {
        return userDao.selectCondition(name, address);
    }
}
